package com.module.lemlin.http

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import retrofit2.http.Url
import rxhttp.RxHttp
import rxhttp.await
import rxhttp.upload
import java.io.File

interface HttpServiceRxHttpApi {

    fun upload2(
        url: String, file: File, listener: ProgressListener? = null
    ): Observable<String> = RxHttp.postForm(url)
        .addFile("file", file)
        .upload(AndroidSchedulers.mainThread()) {
            listener?.onProgress(it)
        }
        .asClass(String::class.java)

    suspend fun upload(
        url: String, path: String, listener: ProgressListener? = null
    ): Any = RxHttp.postForm(url)
        .addFile("file", File(path))
        .upload(CoroutineScope(Dispatchers.Main)) {
            listener?.onProgress(it)
        }.await()

    fun download(
        url: String, destPath: String, listener: ProgressListener? = null
    ): Observable<String> = RxHttp.get(url)
        .asDownload(destPath, AndroidSchedulers.mainThread()) {
            listener?.onProgress(it)
        }

    fun post(url: String, jsonString: String): Observable<Any> = RxHttp.postJson(url)
        .addAll(jsonString)
        .asClass(Any::class.java)

    fun post(url: String, maps: Map<String, Any>): Observable<Any> = RxHttp.postJson(url)
        .addAll(maps)
        .asClass(Any::class.java)
}

interface HttpServiceRetrofitApi {

    @Multipart
    @POST
    fun upload(
        @Url url: String,
        @Part description: RequestBody,
        @Part file: MultipartBody.Part
    ): Observable<String>

}